import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { UsersEntity } from '../entities/user.entity';
import { Repository, UpdateResult, getConnection } from 'typeorm';
import { CommonResponse, ObjectType } from 'src/types/index';
import { UserRoleEntity } from '../entities/user_role.entity';
import { RoleEntity } from 'src/role/role.entity';
import { PostsEntity } from 'src/posts/posts.entity';
import { responseWrapper } from 'src/utils';
import * as jwt from 'jwt-simple';
const secret = 'zhufeng';
@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(UsersEntity)
    private readonly userRepo: Repository<UsersEntity>,
  ) {}

  async createUser(data: ObjectType): Promise<UsersEntity> {
    const user = await this.userRepo.create(data);
    return await this.userRepo.save(user);
  }

  // 逻辑删除
  async deleteUserById(id: number): Promise<UpdateResult> {
    return await this.userRepo.update(id, { isDel: 1 });
  }

  // 更新数据
  async modifyUserById(id: number, data: ObjectType): Promise<UpdateResult> {
    return await this.userRepo.update(id, data);
  }

  // 用户列表
  async userList(): Promise<any> {
    // 简单查询
    // return await this.userRepo.find();
    // 复杂查询
    return await getConnection()
      .createQueryBuilder(UsersEntity, 'user')
      .orderBy({ 'user.createdAt': 'DESC' }) // 排序字段
      .leftJoin(UserRoleEntity, 'user_role', 'user.id=user_role.userId')
      .leftJoinAndMapMany(
        'user.role',
        RoleEntity,
        'role',
        'user_role.role_id=role.id',
      )
      .leftJoinAndMapMany(
        'user.posts',
        PostsEntity,
        'posts',
        'user.id=posts.user_id',
      )
      .printSql()
      .getMany();
  }

  async userById(id: number): Promise<UsersEntity> {
    return await this.userRepo.findOne(id);
  }

  // 登录
  async login(data: ObjectType): Promise<CommonResponse> {
    const user = await this.userRepo.findOne({ username: data.username });
    if (user) {
      if (user.password === data.password) {
        return responseWrapper({
          user,
          token: jwt.encode({ username: data.username }, secret),
        });
      }
      return responseWrapper('密码错误', true);
    }

    return responseWrapper('用户不存在', true);
  }
}
